package com.pinyou.web.service;

import com.pinyou.common.utils.ThreadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Map;


/**
 * @Title: GoodsHtmlService
 * @Description:
 * @Auther:jzfai
 * @Version: 1.0
 * @create 2020/3/11 18:48
 */
@Service
public class GoodsHtmlService {
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private TemplateEngine templateEngine;

    private static final Logger LOGGER= LoggerFactory.getLogger(GoodsHtmlService.class);
    /**
     * 创建html页面
     * @param spuId
     * @throws Exception
     */
    public void createHtml(Long spuId)  {
        // 获取页面数据
        Map<String, Object> spuMap = this.goodsService.loadData(spuId);
        // 创建thymeleaf上下文对象
        Context context = new Context();
        // 把数据放入上下文对象
        context.setVariables(spuMap);
        // 创建输出流
        File file = new File("D:\\java\\javaproject\\pinyou\\pinyou-goods-web\\src\\main\\resources\\thymeleaf\\" + spuId + ".html");
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(file);
        } catch (FileNotFoundException e) {
            LOGGER.error("页面静态化出错：{}，"+ e, spuId);
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
        // 执行页面静态化方法
        templateEngine.process("item",context,writer);
    }

    public void deleteHtml(Long id) {
        File file = new File("D:\\java\\javaproject\\pinyou\\pinyou-goods-web\\src\\main\\resources\\thymeleaf\\" + id + ".html");
        file.deleteOnExit();
    }

    /**
     * 新建线程处理页面静态化
     * @param spuId
     */
    public void asyncExcute(Long spuId) {
        ThreadUtils.execute(()->createHtml(spuId));
    }
}
